import $service from '../../../../service'
let id; // 处方id
let paymentMethod;
let page = 1;
let thenS_;
let tapMap_type;
let template_prescriptionList = {} //保存模板list
let bcmb_diagnosis_id;
var druglistStorage_z = []; //已选中药处方 列表
var druglistStorage_x = []; //已选西药处方 列表
// 西药开处方计算用Obj
var medicineObj = null;
var StorageJosn; //生成处方
var prescriptionListlength = []; //已生成处方list
const app = getApp()
Page({
  data: {
    drug_type: 2,
    openPageBox: 16,
    openPageBox_up: 0,
    tapactive: 1, //处方选项卡
    class_name: '', //类型名称
    class_id: '', // 类型id
    drugClassList: [], //药品类型数组
    drugList: [],
    drugList2: [],
    drugList3: [], // 模版数组
    drugList4: [], // 历史处方
    loadingText: '',
    loadingType: true,
    drug_name: '', //搜索药品名称
    ypxx_drugMap: null, // 药品详情数据
    consumptionlist: [], //用量单位list
    list: [], //用法list
    list2: [], //频次list
    list3: [], //嘱托list
    details_usage: '', //用法
    details_consumption: '', //用量
    details_consumption_util: '', //用量单位
    details_frequency: '', ///频率,
    details_frequency_str: '',
    details_frequency_str2: '',
    details_day: '', //天数
    details_num: '', //盒数
    detailsEntrust: '', //嘱托
    islist: false, //弹窗显示隐藏
    islist2: false, //弹窗显示隐藏
    islist3: false, //弹窗显示隐藏
    isconsumptionlist: false, //弹窗显示隐藏
    drug_packaging_unit: '', //盒数单位
    getdruglistStoragelist: [], //已选处方
    sccfisshow: 0, //开药显示
    prescription_price: 0, //处方金额
    prescription_taking: '', //服用方法
    prescription_requirements: '', //服用要求
    prescription_num: '', //付数
    prescription_isdetalis: false, //生成中药弹窗
    frequency_num: 0,
    frequency_day_num: 0,
    selectionunit: 0,
    drug_packaging_num: 1,
    isdetalis: false, //处方 查看详情
    diagnosisMap: [], //处方 模板详情
    prescriptionMap: {}, //处方 模板详情列表
    drugMap: {}, //开药详情
    bcmb_icd_id: '', //保存模板分类id
    bcmb_icd_name: '', //分类名称
    bcmb_bz: '', //备注
    bcmb_prescription_price: '0', //处方价格
    bcmb_prescription_name: '', //处方名称
    bcmb_prescription_taking: '', //服用方法
    bcmb_prescription_requirements: '', //服用要求
    bcmb_prescription_num: '', //付数
    bcmb_list: [],
    bcmb_list2: [],
    bcmb_diagnosisList: [],
    bcmb_queryName: '',
    bcmb_isullist: false,
    bcmb_type: 0,
    isHis: false
  },
  onLoad: function (e) {
    id = e.id
    paymentMethod = e.paymentMethod
    this.setData({
      isHis: e.storeId == 0? true : false
    })
    thenS_ = this.data
    this.getDrugFrequencyList();
    this.editorPrescription();
  },

  onShow: function () {},
  // 上啦刷新
  onPullDownRefresh() {
    page = 1;
    this.setData({
      loadingText: '加载更多'
    })
    this.getalldo();
    wx.stopPullDownRefresh()
  },
  // 下啦加载
  onReachBottom: function () {
    if (thenS_.loadingType == true && thenS_.openPageBox == 15) {
      page++
      this.getalldo();
    } else {
      this.setData({
        loadingText: '没有更多了'
      })
    }
  },
  // 点击加载
  loading() {
    if (thenS_.loadingType == true) {
      page++
      this.getalldo()
    } else {
      this.setData({
        loadingText: '没有更多了'
      })
    }
  },
  // 获取处方详情
  editorPrescription() {
    app.http.editorPrescription({
      id: id
    }).then(res => {
      let {
        prescriptionType,
        prescriptionDrugListResps,
        prescriptionNum,
        prescriptionRequirements,
        prescriptionTaking
      } = res.data
      this.setData({
        drug_type: prescriptionType
      })
      if (prescriptionType == 1) {
        $service.setStore('druglistStorage_z', JSON.stringify(prescriptionDrugListResps))
        this.setData({
          prescription_taking: prescriptionTaking,
          prescription_requirements: prescriptionRequirements,
          prescription_num: prescriptionNum
        })
        this.publicUtil_getInquiryLoggetUtilTable()
      } else {
        $service.setStore('druglistStorage_x', JSON.stringify(prescriptionDrugListResps))
      }
      this.getalldo();
      this.getdruglistStorage();
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  //用药tab切换
  taptab(e) {
    var index = e.currentTarget.dataset.index;
    if (index != 2) {
      thenS_.class_id = ''
      thenS_.class_name = '全部'
    } else {
      if (!thenS_.drugClassList) {
        thenS_.class_id = ''
        thenS_.class_name = ''
      } else {
        if (thenS_.drug_type == 2) {
          // thenS_.class_id = thenS_.drugClassList[0].id
          // thenS_.class_name = thenS_.drugClassList[0].className
        }
      }
    }
    this.setData({
      tapactive: index,
      drugList: [],
      drugList2: [],
      drugList3: [],
      drugList4: [],
      class_id: thenS_.class_id,
      drug_name: '',
      class_name: thenS_.class_name
    })
    page = 1
    this.getalldo()
  },
  getalldo() {
    if (thenS_.tapactive == 1 || thenS_.tapactive == 2) {
      // 药品目录和分类
      this.getDrugClass();
      this.getDrugList(0);
    } else if (thenS_.tapactive == 3) {
      this.getDrugList(1);
    } else if (thenS_.tapactive == 4) {
      this.getPrescriptionTemplateList(0);
    } else if (thenS_.tapactive == 5) {
      this.getPrescriptionTemplateList(1);

      //   this.doctorSide_personal_prescription_getUtilPrescription()  
    } else if (thenS_.tapactive == 6) {
      //   this.doctorSide_personal_prescription_getHistoryPrescriptionList()
      this.getOpenedPrescription();
    }
  },
  //西药、中药列表、分类，个人
  getDrugList(isPublic = 0) {
    var params = {
      "drugType": Number(thenS_.drug_type),
      "classId": thenS_.class_id,
      "current": Number(page),
      "drugName": thenS_.drug_name,
      "size": 10,
      "isPublic": isPublic,
    }
    app.http.getDrugList(params).then(res => {
      var drugList = res.data.list; //药品列表
      if (drugList) {
        for (var i = 0; i < drugList.length; i++) {
          drugList[i].drug_usname = $service.nothingFun(drugList[i].drug_usname, '--')
        }
      }
      if (page == 1) {
        thenS_.loadingText = '';
        thenS_.drugList = drugList;
        thenS_.loadingType = true;
      } else {
        if (!drugList || drugList.length == 0) {
          thenS_.loadingType = false;
          thenS_.loadingText = '没有更多了';
        } else {
          for (var i = 0; i < drugList.length; i++) {
            thenS_.drugList.push(drugList[i]);
            thenS_.loadingText = '加载更多';
          }
        }
      }
      if (isPublic === 0) {
        this.setData({
          drugList: thenS_.drugList,
        })
      } else {
        this.setData({
          drugList2: thenS_.drugList,
        })
      }
      this.setData({
        loadingText: thenS_.loadingText,
        loadingType: thenS_.loadingType,
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  // 获取药品类型
  getDrugClass() {
    app.http.getDrugClass().then(res => {
      this.setData({
        drugClassList: res.data
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  //个人、公共模板
  getPrescriptionTemplateList(isPublic) {
    let params = {
      "current": page,
      "isPublic": isPublic,
      "prescriptionType": thenS_.drug_type,
      "size": 10
    }
    app.http.getPrescriptionTemplateList(params).then(res => {
      var drugList = res.data.list; //列表
      if (page == 1) {
        thenS_.loadingText = '';
        thenS_.drugList3 = drugList;
      } else {
        if (drugList.length <= 0) {
          thenS_.loadingType = false;
          thenS_.loadingText = '没有更多了';
        } else {
          for (var i = 0; i < drugList.length; i++) {
            thenS_.drugList3.push(drugList[i]);
            thenS_.loadingText = '加载更多';
          }
        }
      }
      this.setData({
        drugList3: thenS_.drugList3,
        loadingText: thenS_.loadingText,
        loadingType: thenS_.loadingType
      })
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
  //历史处方
  getOpenedPrescription() {
    let params = {
      // "inquiryPatientId": inquiryPatientId,
      "prescriptionType": thenS_.drug_type
    }
    app.http.getOpenedPrescription(params).then(res => {
      var drugList = res.data.list; //列表
      this.setData({
        drugList4: drugList,
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  //分类选择
  tapisshow(e) {
    this.data.isshow = !this.data.isshow;
    this.setData({
      isshow: this.data.isshow
    })
  },
  tapchoose(e) {
    var index = e.currentTarget.dataset.index;
    this.data.isshow = !this.data.isshow;
    if (index == -1) {
      thenS_.class_id = '',
        thenS_.class_name = '全部'
    } else {
      console.log(thenS_.drugClassList[index])
      thenS_.class_id = thenS_.drugClassList[index].id,
        thenS_.class_name = thenS_.drugClassList[index].className
    }
    this.setData({
      isshow: this.data.isshow,
      class_id: thenS_.class_id,
      class_name: thenS_.class_name
    })
    page = 1
    this.getalldo()
  },
  // 药品名称搜索
  xzypinputChange(e) {
    this.setData({
      drug_name: e.detail.value
    })
    page = 1
    this.getalldo()
  },
  //点击按钮
  async tapdrugList(e) {
    var this_ = this;
    var type = e.currentTarget.dataset.type; //0目录、分类 1个人用药 2个人、公共模板 3历史处方
    var index = e.currentTarget.dataset.index; //下标
    var num = e.currentTarget.dataset.num; //1保存用药
    thenS_.openPageBox_up = thenS_.openPageBox;
    if (num == 1) { //1保存用药
      app.http.addPersonalDrug({
        id: this.data.drugList[index].id
      }).then(res => {
        $service.showToast(res.msg);
      }).catch(err => {
        $service.showToast(err.msg);
      })
    } else if (num == 2) { //详情
      if (type == 0) {
        var id = this.data.drugList[index].id
      } else if (type == 1) {
        var id = this.data.drugList2[index].id
      } else if (type == 4) {
        var id = this.data.diagnosisMap.drugList[index].id
      }
      thenS_.openPageBox = 21
      this.publicUtil_getDrugDetail(id)
    } else if (num == 3) { //开药
      if (type == 0) {
        var drugMap = this.data.drugList[index]
      } else if (type == 1) {
        var drugMap = this.data.drugList2[index]
      }
      thenS_.openPageBox = 16;

      this.setData({
        drugMap: drugMap,
        sccfisshow: 1,
        details_usage: '', //用法
        details_consumption: '', //用量
        details_consumption_util: '', //用量单位
        details_frequency: '', ///频率,
        details_frequency_str: '',
        details_frequency_str2: '',
        details_day: '', //天数
        details_num: '', //盒数
        detailsEntrust: '', //嘱托
        islist: false, //弹窗显示隐藏
        islist2: false, //弹窗显示隐藏
        islist3: false, //弹窗显示隐藏
        isconsumptionlist: false, //弹窗显示隐藏
        drug_packaging_unit: '', //盒数单位
        getdruglistStoragelist: [], //已选处方
        prescription_price: 0, //处方金额
        prescription_taking: '', //服用方法
        prescription_requirements: '', //服用要求
        prescription_num: '', //付数
        prescription_isdetalis: false, //生成中药弹窗
        frequency_num: 0,
        frequency_day_num: 0,
        selectionunit: 0,
        drug_packaging_num: 1

      })
      this.getpageScrollTo()
      //   this.publicUtil_getInquiryLogDetails()
      this.publicUtil_getDrugDetail2('1') //药品详情
      this.publicUtil_getInquiryLoggetUtilTable() //工具
      this.getdruglistStorage()
    } else if (num == 4) { //删除个人用药/个人模板
      if (type == 1) {
        var drugMap = this.data.drugList2[index]
        var content = '确定要删除当前常用药品？'
      } else if (type == 2) {
        var drugMap = this.data.drugList3[index]
        var content = '确定要删除当前常用模板？'
      }
      wx.showModal({
        title: '温馨提示',
        content: content,
        success(res) {
          if (res.confirm) {
            if (type == 1) { //删除个人用药
              app.http.deletePersonalDrug({
                id: thenS_.drugList2[index].drugTemplateId
              }).then(res => {
                page = 1
                $service.showToast(res.msg)
                this_.getalldo()
              }).catch(err => {
                $service.showToast(err.msg)
              })
            } else if (type == 2) { //删除个人模板
              console.log(thenS_.drugList3[index])
              app.http.deletePrescriptionTemplate({
                id: thenS_.drugList3[index].id
              }).then(res => {
                page = 1
                $service.showToast(res.msg)
                this_.getalldo()
              }).catch(err => {
                $service.showToast(err.msg)
              })
            }
          }
        }
      })
    } else if (num == 5 || num == 6 || num == 7) { //引用处方5 //查看模板6 7另存模板
      tapMap_type = 0
      if (type == 2) { //模板的
        thenS_.diagnosisMap = thenS_.drugList3[index]
      } else if (type == 3) { //历史处方的
        thenS_.diagnosisMap = thenS_.drugList4[index];
        thenS_.diagnosisMap.drugList = thenS_.drugList4[index].detailsResps
      }
      if (num == 5) {
        if (this.data.drug_type == 1) { //已选中 中药 、、存缓存
          druglistStorage_z = [];
          druglistStorage_z = type == 2 ? thenS_.drugList3[index].drugList : thenS_.drugList4[index].drugList
          //   let {prescriptionTaking, prescriptionRequirements, prescriptionNum} = type == 2 ? thenS_.drugList3[index] : thenS_.drugList4[index]
          //   this.setData({
          //     prescription_taking: prescriptionTaking,
          //     prescription_requirements: prescriptionRequirements,
          //     prescription_num: prescriptionNum
          //   })
          wx.setStorageSync("druglistStorage_z", JSON.stringify(druglistStorage_z))
        } else { //已选中 西药 、、存缓存
          druglistStorage_x = [];
          druglistStorage_x = type == 2 ? thenS_.drugList3[index].drugList : thenS_.drugList4[index].drugList
          wx.setStorageSync("druglistStorage_x", JSON.stringify(druglistStorage_x))
        }
        this.getdruglistStorage();
        $service.showToast('引用成功')
      } else if (num == 6) {
        tapMap_type = 1;
        this.setData({
          diagnosisMap: thenS_.diagnosisMap,
          isdetalis: true
        })
      } else if (num == 7) {
        tapMap_type = 2;
        thenS_.openPageBox_up = thenS_.openPageBox;
        this.setData({
          openPageBox: 22,
          openPageBox_up: thenS_.openPageBox_up,
          bcmb_type: 0
        })
        this.getpageScrollTo()
        template_prescriptionList = {
          detailsList: thenS_.drugList4[index].detailsResps,
          prescription_price: thenS_.drugList4[index].prescriptionPrice
        }
        this.publicUtil_getUtilTable78()
      }
    } else if (num == 8) { //关闭弹窗
      this.setData({
        isdetalis: false
      })
    } else if (num == 9) {
      thenS_.openPageBox = 16
      this.getdruglistStorage()
      this.setData({
        sccfisshow: 0
      })
    }
    this.setData({
      openPageBox: thenS_.openPageBox,
      openPageBox_up: thenS_.openPageBox_up
    })
  },
  //药品详情
  publicUtil_getDrugDetail2: function (type) {
    try {
      if (this.data.isHis) { // 院内处方
        app.http.getDrugInfo({
          "drugCode": thenS_.drugMap.id,
          "drugType": Number(thenS_.drug_type)
        }).then(res => {
          console.log(res)
        })
      } else {
        var params = {
          "id": thenS_.drugMap.id
        }
        app.http.getDrugInfo(params).then(res => {
          var drugMap = res.data;
          medicineObj = drugMap;
          if (type === '1') { // 开要设置默认用法
            this.publicUtil_getInquiryLoggetUtilTable() //工具
            this.setData({
              details_usage: this.data.drug_type == "1" ? drugMap.usageType : drugMap.drugUsage || "",
              details_consumption: drugMap.usageNum || "",
              details_consumption_util: drugMap.drugUnit || drugMap.drugVolumeUnit,
              details_frequency_str2: drugMap.frequency || "",
              details_frequency: drugMap.frequencyId || "",
              details_frequency_str: drugMap.frequencyName || "",
              frequency_num: drugMap.frequencyNum || "", // 频次数
              frequency_day_num: drugMap.frequencyTime || "", // 频率时间间隔 
              detailsEntrust: drugMap.enjoin || "",
              details_day: drugMap.drugMaxday || "",
              selectionunit: drugMap.drugUnit ? '5' : '2' // 如果药品单位有则使用5的数据计算药品 没有则用2
            })
            if (this.data.drug_type == "2") this.jisuanxiyaochufangshuliang()
          }
          this.setData({
            consumptionlist: drugMap.consumptionList,
            drug_packaging_unit: drugMap.drugPackagingUnit,
          })
        })

      }
    } catch (err) {
      $service.showToast(err.msg)
    }
  },
  //问诊详情
  getdruglistStorage() {
    if (thenS_.drug_type == 1) { //1中药
      if (!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_z"))) {
        var list = $service.strToJson(wx.getStorageSync("druglistStorage_z"));
      } else {
        var list = []
      }
      druglistStorage_z = list; //已选中药处方 列表

    } else if (thenS_.drug_type == 2) {
      if (!$service.isUndefinedAndEmpty(wx.getStorageSync("druglistStorage_x"))) {
        var list = $service.strToJson(wx.getStorageSync("druglistStorage_x"));
      } else {
        var list = []
      }
      druglistStorage_x = list; //已选西药处方 列表
    }
    var drug_price = 0;
    for (var i = 0; i < list.length; i++) {
      if ($service.isUndefinedAndEmpty(list[i].drugPrice)) {
        list[i].drugPrice = 0
      }
      drug_price += $service.strToFloat(list[i].drugPrice) * $service.strToInt(list[i].detailsNum);
    }
    this.setData({
      getdruglistStoragelist: list,
      prescription_price: drug_price
    })
  },
  publicUtil_getInquiryLoggetUtilTable: function () {
    if (thenS_.drug_type == 2) {
      this.getDrugUsageList(1)
    } else {
      this.getDrugUsageList(2)
      this.getDrugUsageList(3)
      this.getDrugUsageList(4)
    }
  },
  tap_usage(e) {
    var num = e.currentTarget.dataset.index;
    if (num == 0) { //用法
      thenS_.islist = !thenS_.islist
      thenS_.isconsumptionlist = false
    } else if (num == 1) { //用量单位
      thenS_.isconsumptionlist = !thenS_.isconsumptionlist
      thenS_.islist = false
    } else if (num == 2 || num == 4) { //频次
      thenS_.islist2 = !thenS_.islist2
      thenS_.islist3 = false
    } else if (num == 3 || num == 5) { //嘱托
      thenS_.islist3 = !thenS_.islist3
      thenS_.islist2 = false
    }
    this.setData({
      islist: thenS_.islist,
      islist2: thenS_.islist2,
      islist3: thenS_.islist3,
      isconsumptionlist: thenS_.isconsumptionlist
    })
  },
  //选择用法、用量单位、频次、嘱托
  chooselist(e) {
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.num;
    if (num == 0) { //用法
      thenS_.details_usage = this.data.isHis ? thenS_.list[index].dictName : thenS_.list[index].usageName
    } else if (num == 1) { //用量单位
      if (this.data.isHis ) { // 廉江his选择药品单位
        thenS_.details_consumption_util = thenS_.consumptionlist[index].dictName
      } else {
        thenS_.details_consumption_util = thenS_.consumptionlist[index]
        this.jisuanxiyaochufangshuliang()
      }
    } else if (num == 2) { //频次
      if (!this.data.isHis) {
        thenS_.details_frequency = thenS_.list2[index].id
        thenS_.details_frequency_str = thenS_.list2[index].frequencyPrintingName
        thenS_.details_frequency_str2 = thenS_.list2[index].frequencyName
        this.setData({ // 11
            frequency_num: thenS_.list2[index].frequencyNum,
            frequency_day_num: thenS_.list2[index].frequencyHoursNum
        });
        this.jisuanxiyaochufangshuliang()
      } else {  // 是否是廉江院内药店
        thenS_.details_frequency = thenS_.list2[index].dictCode
        thenS_.details_frequency_str = thenS_.list2[index].dictName
        thenS_.details_frequency_str2 = thenS_.list2[index].dictName
      }
    } else if (num == 3) { //嘱托
      thenS_.detailsEntrust = thenS_.list2[index].advice_name
    } else if (num == 4) { //服用方法
      thenS_.prescription_taking = thenS_.list2[index].usageName
    } else if (num == 5) { //服用要求
      thenS_.prescription_requirements = thenS_.list3[index].usageName
    }
    this.setData({
      details_usage: thenS_.details_usage,
      details_consumption_util: thenS_.details_consumption_util,
      details_frequency: thenS_.details_frequency,
      details_frequency_str2: thenS_.details_frequency_str2,
      details_frequency_str: thenS_.details_frequency_str,
      detailsEntrust: thenS_.detailsEntrust,
      prescription_taking: thenS_.prescription_taking,
      prescription_requirements: thenS_.prescription_requirements,
      islist: false,
      islist2: false,
      islist3: false,
      isconsumptionlist: false
    })
  },
  //input监听
  inputChange(e) {
    var index = e.currentTarget.dataset.index;
    if (index == 1) { //用量
      let reg = /^\d+(\.\d+)?$/;
      if (!reg.test(e.detail.value)) {
        $service.showToast('请输入正确的用量')
        thenS_.details_consumption = 1
      } else {
        thenS_.details_consumption = parseFloat(e.detail.value)
      }
    } else if (index == 2) { //天数
      thenS_.details_day = e.detail.value
    } else if (index == 3) { //盒数
      thenS_.details_num = e.detail.value
    } else if (index == 4) { //嘱托
      thenS_.detailsEntrust = e.detail.value
    } else if (index == 5) { //付数
      thenS_.prescription_num = e.detail.value
    }
    this.setData({
      details_consumption: thenS_.details_consumption,
      details_day: thenS_.details_day,
      details_num: thenS_.details_num,
      detailsEntrust: thenS_.detailsEntrust,
      prescription_num: thenS_.prescription_num
    })
  },
  //input监听
  inputChange2(e) {
    var index = e.currentTarget.dataset.index;
    if (index == 1) { //用量
      thenS_.details_consumption = e.detail.value
    } else if (index == 2) { //天数
      thenS_.details_day = e.detail.value
    } else if (index == 5) {
      thenS_.prescription_num = e.detail.value
    }
    this.setData({
      details_num: thenS_.details_num,
      details_consumption: thenS_.details_consumption,
      details_day: thenS_.details_day,
      prescription_num: thenS_.prescription_num
    })
    if (index == 1) { //用量
      this.jisuanxiyaochufangshuliang()
    } else if (index == 2) { //天数
      this.jisuanxiyaochufangshuliang()
    }
  },
  tap_reduce_add(e) {
    var index = e.currentTarget.dataset.index;
    if ($service.isUndefinedAndEmpty(thenS_.details_consumption)) {
      thenS_.details_consumption = 0
    }
    if (index == 0) {
      thenS_.details_consumption--
      if (thenS_.details_consumption <= 0) {
        $service.showToast('用量不能小于0');
        thenS_.details_consumption = 1
      }
    } else {
      thenS_.details_consumption++
    }
    this.setData({
      details_consumption: thenS_.details_consumption
    })
  },
  // 计算药品
  jisuanxiyaochufangshuliang() {
    if (this.data.details_frequency_str2) {
      this.data.list2.forEach(item => {
        if (item.frequencyPrintingName == this.data.details_frequency_str2) {
          this.setData({
            frequency_day_num: item.frequencyHoursNum,
            frequency_num: item.frequencyNum
          })
        }
      })
    }
    if (this.data.details_consumption && this.data.details_day && this.data.frequency_num && this.data.frequency_day_num && this.data.details_consumption_util) {
      let params = {
        "bigPackaging": medicineObj.goodsBigPacking,
        "days": Number(this.data.details_day),
        "dosage": this.data.details_consumption,
        "drugSpecification": medicineObj.goodsGuige,
        "frequencyHoursNum": this.data.frequency_day_num,
        "frequencyNum": this.data.frequency_num,
        "mediumPackaging": medicineObj.goodsMediumPacking,
        "smallestPackaging": medicineObj.drugPackagingNum,
        "usageUnit": this.data.details_consumption_util,
        "usageUnitId": Number(medicineObj.id),
        "drugVolumeUnit": medicineObj.drugVolumeUnit,
        "drugSmallestUnit": medicineObj.drugSmallestUnit,
        "drugUnit": medicineObj.drugUnit
      }
      app.http.getTheCalculationFormula(params).then(res => {
        this.setData({
          details_num: res.data.quantityOfMedication
        })
      })
    }
  },
  //生成处方
  qrBtn(e) {
    var index = e.currentTarget.dataset.index;
    thenS_.openPageBox_up = thenS_.openPageBox;
    if (index == 1) { //生成已选处方（未开）
      var detailsList = []
      if ($service.isUndefinedAndEmpty(thenS_.details_consumption)) {
        $service.showToast('请先输入用量');
        return;
      }
      if (Number(thenS_.details_consumption) <= 0) {
        $service.showToast('请先输入正确用量');
        return;
      }
      if ($service.isUndefinedAndEmpty(thenS_.details_consumption_util)) {
        $service.showToast('请先选择用量单位');
        return;
      }

      if (thenS_.drug_type == 1) { //1中药
        if ($service.isUndefinedAndEmpty(thenS_.details_num)) {
          $service.showToast('请输入数量');
          return;
        }
        if (thenS_.details_num < 1) {
          $service.showToast('数量不能小于1');
          return;
        }
        for (var i = 0; i < druglistStorage_z.length; i++) { //判断缓存是否有相同的，先删除再添加
          if (druglistStorage_z[i].drugId == thenS_.drugMap.id) {
            druglistStorage_z.splice(i, 1)
          }
        }
        StorageJosn = {
          "detailsConsumption": thenS_.details_consumption,
          "detailsConsumptionUnit": thenS_.details_consumption_util,
          "detailsUsage": thenS_.details_usage,
          "drugPrice": thenS_.drugMap.drugPrice,
          "drugName": thenS_.drugMap.drugName,
          "drugId": thenS_.drugMap.id,
          "storeId": thenS_.drugMap.storeId,
          "storeName": thenS_.drugMap.storeName,
          "detailsNum": thenS_.details_consumption
        }
        for (var i = 0; i < druglistStorage_z.length; i++) {
          var drugid = {
            "drug_id": druglistStorage_z[i].drugId
          }
          detailsList.push(drugid)
        }
      } else { //2西药
        if ($service.isUndefinedAndEmpty(thenS_.details_frequency_str)) {
          $service.showToast('请先选择频次');
          return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.details_day)) {
          $service.showToast('请先输入天数');
          return;
        }
        if (thenS_.details_day > 90) {
          $service.showToast('天数不能大于90天');
          return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.details_num)) {
          $service.showToast('请输入数量');
          return;
        }
        if (thenS_.details_num < 1) {
          $service.showToast('数量不能小于1');
          return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.details_usage)) {
          $service.showToast('请选择用法');
          return;
        }
        console.log(druglistStorage_x)
        for (var i = 0; i < druglistStorage_x.length; i++) { //判断缓存是否有相同的，先删除再添加
          if (druglistStorage_x[i].drugId == thenS_.drugMap.id) {
            druglistStorage_x.splice(i, 1)
          }
        }
        StorageJosn = {
          "frequency_num": thenS_.frequency_num,
          "frequency_day_num": thenS_.frequency_day_num,
          "drugSpecifications": thenS_.drugMap.drugSpecifications,
          "detailsConsumption": thenS_.details_consumption,
          "detailsConsumptionUnit": thenS_.details_consumption_util,
          "detailsFrequencyStr": thenS_.details_frequency_str,
          "detailsFrequencyStr2": thenS_.details_frequency_str2,
          "detailsFrequency": thenS_.details_frequency,
          "detailsDay": thenS_.details_day,
          "detailsNum": thenS_.details_num,
          "detailsUsage": thenS_.drug_type == 2 ? thenS_.details_usage : '',
          "detailsEntrust": thenS_.detailsEntrust,
          "drugPrice": thenS_.drugMap.drugPrice,
          "drugName": thenS_.drugMap.drugName,
          "drugId": thenS_.drugMap.id,
          "storeId": thenS_.drugMap.storeId,
          "storeName": thenS_.drugMap.storeName,
        }
        for (var i = 0; i < druglistStorage_x.length; i++) {
          var drugid = {
            "drug_id": druglistStorage_x[i].drugId
          }
          detailsList.push(drugid)
        }
      }
      console.log(StorageJosn);
      this.setDurgStorage()
    } else if (index == 2) { //保存模板
      if (thenS_.drug_type == 1) { //1中药
        var detailsList = druglistStorage_z;
      } else {
        var detailsList = druglistStorage_x;
      }
      if (detailsList.length == 0) {
        $service.showToast('请先开处方');
        return;
      }
      thenS_.openPageBox_up = thenS_.openPageBox
      this.setData({
        openPageBox: 22,
        openPageBox_up: thenS_.openPageBox_up,
        bcmb_type: 0
      })
      this.getpageScrollTo()
      template_prescriptionList = { //保存模板
        detailsList: detailsList,
        prescription_price: thenS_.prescription_price
      }
      this.publicUtil_getUtilTable78()
    } else if (index == 3) { //生成处方 （已开）
      if (prescriptionListlength.length >= 5) {
        $service.showToast('处方不能超过5个');
        return;
      }
      if (thenS_.drug_type == 1) { //1中药
        var list = druglistStorage_z;
      } else {
        var list = druglistStorage_x;
      }
      if (list.length == 0) {
        $service.showToast('请先开处方');
        return;
      }
      if (thenS_.drug_type == 1) {
        if (this.data.isHis) {
          this.getDictInfo(103)
        }
        this.setData({
          prescription_isdetalis: true
        })
      } else {
        this.doctorSide_personal_prescription_addInquiryLogPrescription()
      }
    } else if (index == 4) { //取消
      this.setData({
        prescription_isdetalis: false
      })
    } else if (index == 5) { //中药生成处方
      if ($service.isUndefinedAndEmpty(thenS_.prescription_taking)) {
        $service.showToast('请选择服用方法');
        return;
      }
      if ($service.isUndefinedAndEmpty(thenS_.prescription_num)) {
        $service.showToast('请输入付数');
        return;
      }
      this.doctorSide_personal_prescription_addInquiryLogPrescription()
    }
  },
  //把选中药品储存到缓存
  setDurgStorage() {
    if (thenS_.drug_type == 1) { //1中药
      druglistStorage_z.push(StorageJosn)
      wx.setStorageSync("druglistStorage_z", $service.jsonToStr(druglistStorage_z))
    } else { //2西药
      if (druglistStorage_x.length >= 5) {
        $service.showToast('最多5个');
      } else {
        druglistStorage_x.push(StorageJosn)
      }
      console.log(druglistStorage_x)
      wx.setStorageSync("druglistStorage_x", $service.jsonToStr(druglistStorage_x))
    }
    this.getdruglistStorage()
    this.setData({
      sccfisshow: 0
    })
  },
  //开药（生成处方）
  async doctorSide_personal_prescription_addInquiryLogPrescription() {
    wx.showLoading({
      title: '生成中',
    })
    var this_ = this;
    if (thenS_.drug_type == 1) { //1中药
      var list = druglistStorage_z;
    } else {
      var list = druglistStorage_x;
    }
    try {
      if (this.data.isHis) {
        let checkParams = {
          "cardType": "",
          "detailInfo": [],
          "healthCardNo": "",
          "patientName": "",
          "patientType": 0
        }
        list.forEach(item => {
          checkParams.detailInfo.push({
            "detailCount": item.detailsNum,
            "detailId": item.drugId,
            "detailName": item.drugName,
            "detailUnit": item.drugPackagingUnit
          })
        })
        let res = await app.http.checkPrice(checkParams)
        this.setData({
          prescription_price: res.totalPrice
        })
      }
      let params = {
        "drugs": list,
        "id": Number(id),
        "prescriptionPrice": String(thenS_.prescription_price),
        "storeId": list[0].storeId,
        "storeName": list[0].storeName,
        "paymentMethod": paymentMethod,
        "prescriptionType": thenS_.drug_type,
      }
      if (thenS_.drug_type == 1) {
        params.prescriptionNum = thenS_.prescription_num; //付数 中药时使用
        params.prescriptionTaking = thenS_.prescription_taking; //服用方法 中药时使用
        params.prescriptionRequirements = thenS_.prescription_requirements; //服用要求 中药时使用
      }
      console.log('生成处方', params)
      app.http.updatePrescription(params).then(res => {
        if (thenS_.drug_type == 1) { //1中药
          druglistStorage_z = []
          wx.setStorageSync("druglistStorage_z", $service.jsonToStr(druglistStorage_z))
        } else {
          druglistStorage_x = []
          wx.setStorageSync("druglistStorage_x", $service.jsonToStr(druglistStorage_x))
        }
        this.setData({
          prescription_isdetalis: false,
        })
        $service.showToast(res.msg);
        setTimeout(() => {
          wx.navigateBack();
        }, 500)
      })
      wx.hideLoading()
    } catch (err) {
      $service.showToast(err.msg);
      wx.hideLoading()
    }
  },
  //删除、编辑
  storagelist(e) {
    var index = e.currentTarget.dataset.index; //下标
    var num = e.currentTarget.dataset.num; //1编辑 2删除
    if (num == 1) {
      thenS_.sccfisshow = "1";
      var Map = thenS_.getdruglistStoragelist[index]
      if (this.data.isHis) {
        this.getDictInfo(20)
      }
      if (thenS_.drug_type == 1) {
        if (this.data.isHis) {
          this.getDictInfo(70)
          this.getDictInfo(52)
        }
        this.setData({
          'drugMap.storeName': Map.storeName,
          'drugMap.drugName': Map.drugName,
          'drugMap.id': Map.drugId || Map.id,
          'drugMap.storeName': Map.storeName,
          'drugMap.storeId': Map.storeId,
          'drugMap.drugPrice': Map.drugPrice,
          details_num: Map.detailsNum,
          details_usage: Map.detailsUsage,
          details_consumption_util: Map.detailsConsumptionUnit,
          details_consumption: Map.detailsConsumption,
          sccfisshow: thenS_.sccfisshow
        })
      } else {
        if (!this.data.isHis) {
          this.getDrugUsageList(1)
        } else {
          this.getDictInfo(51)
          this.getDictInfo(60)
        }
        this.setData({
          'drugMap.drugName': Map.drugName,
          'drugMap.storeName': Map.storeName,
          'drugMap.storeId': Map.storeId,
          'drugMap.drugSpecifications': Map.drugSpecifications,
          'drugMap.id': Map.drugId || Map.id,
          'drugMap.drugPrice': Map.drugPrice,
          drug_packaging_unit: Map.drugPackagingUnit,
          frequency_day_num: Map.frequency_day_num,
          frequency_num: Map.frequency_num,
          details_usage: Map.detailsUsage,
          details_consumption_util: Map.detailsConsumptionUnit,
          details_frequency: Map.detailsFrequency,
          details_frequency_str: Map.detailsFrequencyStr,
          details_frequency_str2: Map.detailsFrequencyStr,
          details_consumption: Map.detailsConsumption,
          details_day: Map.detailsDay,
          details_num: Map.detailsNum,
          detailsEntrust: Map.detailsEntrust,
          sccfisshow: thenS_.sccfisshow
        })
      }
      this.publicUtil_getDrugDetail2('2');
      this.getpageScrollTo()
    } else {
      if (thenS_.drug_type == 1) { //1中药
        druglistStorage_z.splice(index, 1)
        wx.setStorageSync("druglistStorage_z", $service.jsonToStr(druglistStorage_z))
      } else {
        druglistStorage_x.splice(index, 1)
        wx.setStorageSync("druglistStorage_x", $service.jsonToStr(druglistStorage_x))
      }
      this.getdruglistStorage()
    }
  },
  //返回上一页
  blck(e) {
    page = 1
    this.setData({
      openPageBox: 15
    })
    this.getalldo()
    this.getpageScrollTo()
  },
  //---------------- 药品详情信息
  //数据
  publicUtil_getDrugDetail: function (drug_id) {
    app.http.getDrugInfo({
      id: drug_id
    }).then(res => {
      var drugMap = res.data;
      drugMap.drugInstructions = $service.nothingFun(drugMap.drugInstructions, '暂无数据');
      this.setData({
        ypxx_drugMap: drugMap
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  //返回顶部
  getpageScrollTo() {
    wx.pageScrollTo({
      scrollTop: 0
    })
  },
  //list 工具
  publicUtil_getUtilTable78: function () {
    this.getDrugUsageList(3);
    this.getDrugUsageList(4)
  },
  //  频次
  getDrugFrequencyList() {
    app.http.getDrugFrequencyList().then(res => {
      this.setData({
        list2: res.data.list
      })
    })
  },
  // 用法
  getDrugUsageList(usageType) {
    app.http.getDrugUsageList({
      usageType: usageType
    }).then(res => {
      switch (usageType) {
        case 1:
          thenS_.list = res.data.list
          break;
        case 2:
          thenS_.list = [...[{id: 0, usageName: '无'}],...res.data.list]
          break;
        case 3:
          thenS_.list2 = res.data.list
          break;
        case 4:
          thenS_.list3 = res.data.list
          break;
      }
      this.setData({
        list: thenS_.list,
        list2: thenS_.list2,
        list3: thenS_.list3
      })
    })
  },

  // 保存模版
  bcmb_tap_usage(e) {
    var num = e.currentTarget.dataset.index;
    if (num == 0) { //服用方法
      thenS_.bcmb_islist = !thenS_.bcmb_islist
      thenS_.bcmb_islist2 = false
    } else if (num == 1) { //服用要求
      thenS_.bcmb_islist2 = !thenS_.bcmb_islist2
      thenS_.bcmb_islist = false
    }
    this.setData({
      bcmb_islist: thenS_.bcmb_islist,
      bcmb_islist2: thenS_.bcmb_islist2
    })
  },
  //选择用法、用量单位、频次、嘱托
  bcmb_chooselist(e) {
    var index = e.currentTarget.dataset.index;
    var num = e.currentTarget.dataset.num;
    if (num == 0) { //用法
      thenS_.bcmb_prescription_taking = thenS_.list[index].usageName == '无' ? '' : thenS_.list[index].usageName
    } else if (num == 1) { //用量单位
      thenS_.bcmb_prescription_requirements = thenS_.list3[index].usageName
    }
    this.setData({
      bcmb_prescription_taking: thenS_.bcmb_prescription_taking,
      bcmb_prescription_requirements: thenS_.bcmb_prescription_requirements,
      bcmb_islist: false,
      bcmb_islist2: false
    })
  },
  //input监听
  bcmb_inputChange(e) {
    var index = e.currentTarget.dataset.index;
    if (index == 1) { //用量
      this.setData({
        bcmb_queryName: e.detail.value
      })
      this.doctorSide_personal_prescription_getDiagnosisList()
    } else if (index == 2) { //天数
      thenS_.bcmb_prescription_name = e.detail.value
    } else if (index == 3) { //盒数
      thenS_.bcmb_prescription_num = e.detail.value
    } else if (index == 4) { //嘱托
      thenS_.bcmb_bz = e.detail.value
    }
    this.setData({
      bcmb_prescription_name: thenS_.bcmb_prescription_name,
      bcmb_prescription_num: thenS_.bcmb_prescription_num,
      bcmb_bz: thenS_.bcmb_bz
    })
  },
  doctorSide_personal_prescription_getDiagnosisList: function () {
    let params = {
      "keyword": this.data.bcmb_queryName
    }
    app.http.getIcdList(params).then(res => {
      console.log(res.data.list)
      var diagnosisList = res.data.list; //列表
      if (diagnosisList.length == 0) {
        thenS_.bcmb_isullist = false;
        this.setData({
          bcmb_icd_name: thenS_.bcmb_icd_name
        })
        $service.showToast('暂无数据，请输入正确的诊断名称')
      } else {
        thenS_.bcmb_isullist = true
      }
      this.setData({
        bcmb_diagnosisList: diagnosisList,
        bcmb_isullist: thenS_.bcmb_isullist
      })
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  tapdiagnosisList(e) {
    var index = e.currentTarget.dataset.index;
    bcmb_diagnosis_id = thenS_.bcmb_diagnosisList[index].id
    if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_name)) {
      thenS_.bcmb_prescription_name = thenS_.bcmb_diagnosisList[index].icdName
    }
    this.setData({
      bcmb_icd_name: thenS_.bcmb_diagnosisList[index].icdName,
      bcmb_prescription_name: thenS_.bcmb_prescription_name,
      bcmb_icd_id: thenS_.bcmb_diagnosisList[index].id,
      bcmb_isullist: false
    })
  },
  bcmb_cancel() {
    this.setData({
      bcmb_isullist: false
    })
  },
  cancel(e) {
    this.setData({
      bcmb_icd_name: thenS_.bcmb_icd_name,
      bcmb_isullist: false
    })
  },
  bcmb_qrBtn() {
    var this_ = this;
    if ($service.isUndefinedAndEmpty(thenS_.bcmb_icd_name)) {
      $service.showToast('请先选择诊断名称');
      return;
    }
    if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_name)) {
      $service.showToast('请先输入模板名称');
      return;
    }
    var jsonData = {
      "icd_id": thenS_.bcmb_icd_id, //疾病分类id
      "diagnosisId": bcmb_diagnosis_id, //	诊断id
      "prescriptionType": thenS_.drug_type, //处方类型 1中药 2西药
      "prescriptionPrice": template_prescriptionList.prescription_price, //	处方金额
      "prescriptionName": thenS_.bcmb_prescription_name, //处方名称 中药时使用
      "remarks": thenS_.bcmb_bz, //备注
      "drugs": template_prescriptionList.detailsList
    }
    if (thenS_.bcmb_type != 1) {
      if (thenS_.drug_type == 1) { //1中药
        if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_taking)) {
          $service.showToast('请先选择服用方法');
          return;
        }
        if ($service.isUndefinedAndEmpty(thenS_.bcmb_prescription_num)) {
          $service.showToast('请先输入付数');
          return;
        }
        jsonData.prescriptionNum = thenS_.bcmb_prescription_num; //付数 中药时使用
        jsonData.prescriptionTaking = thenS_.bcmb_prescription_taking; //服用方法 中药时使用
        jsonData.prescriptionRequirements = thenS_.bcmb_prescription_requirements; //服用要求 中药时使用
      }
    }
    console.log(jsonData)
    app.http.addPrescriptionTemplate(jsonData).then(res => {
      $service.showToast(res.msg)
      this_.getalldo()
      this_.closeBox('', 1)
    }).catch(err => {
      $service.showToast(err.msg);
    })
  },
  // 关闭弹窗
  closeBox(e, num) {
    if (num == 1) {
      var index = 2; //1关闭全部弹窗   2关闭当前弹窗
    } else {
      var index = e.currentTarget.dataset.index; //1关闭全部弹窗   2关闭当前弹窗
    }
    // 1查询病历 2检验检查 3健康指导意见单 4查询图片 5人体示意 6住院建议书 7问诊规范 8结束问诊 9开处方 10修改患者资料 11分诊  12常用语 13 测量数据 
    //14查询历史问诊 15开处方-选择开药 16 开处方-生成处方 17检验检查-心电图 18检验检查-申请单  19健康指导-健康指导意见单详情填写 20填写诊断信息、主诉、过敏史等 21药品信息 22 保存模板 23处方详情 24 检验检查详情 25健康指导详情 26住院建议详情
    var This_openPageBox = 0
    console.log(index)
    if (index == 1) {
      This_openPageBox = 16
    } else {
      if (thenS_.openPageBox == 14) { //查询历史问诊  返回上一弹窗 测量数据
        This_openPageBox = 1
      } else if (thenS_.openPageBox == 15) { //开处方-选择开药  返回上一弹窗 开处方
        This_openPageBox = 16
      } else if (thenS_.openPageBox == 16) { //开处方-生成处方  返回上一弹窗 开处方-选择开药
        This_openPageBox = 16
      } else if (thenS_.openPageBox == 17 || thenS_.openPageBox == 18) { //检验检查-申请单  返回上一弹窗 检验检查
        This_openPageBox = 2
      } else if (thenS_.openPageBox == 19) { //
        This_openPageBox = 3
      } else if (thenS_.openPageBox == 20 || thenS_.openPageBox == 21 || thenS_.openPageBox == 22 || thenS_.openPageBox == 23 || thenS_.openPageBox == 24 || thenS_.openPageBox == 25 || thenS_.openPageBox == 28) { // 返回上一弹窗 
        This_openPageBox = thenS_.openPageBox_up
      } else {
        // 清楚住院建议书备注缓存
        if (thenS_.openPageBox == 6) {
          $service.removeStore('zyjys_bz')
        }
        This_openPageBox = 0
      }
    }
    if (This_openPageBox == 0) {
      // this.bottom()
    }
    this.setData({
      openPageBox: This_openPageBox,
      bcmb_type: 0,
      bcmb_icd_id: '', //保存模板分类id
      bcmb_icd_name: '', //分类名称
      bcmb_bz: '', //备注
      bcmb_prescription_price: '0', //处方价格
      bcmb_prescription_name: '', //处方名称
      bcmb_prescription_taking: '', //服用方法
      bcmb_prescription_requirements: '', //服用要求
      bcmb_prescription_num: '', //付数
      bcmb_list: [],
      bcmb_list2: [],
      bcmb_diagnosisList: [],
      bcmb_queryName: '',
      bcmb_isullist: false,
      sccfisshow: 0
    })
  },

  // 获取his药品用法用量
  getDictInfo(type) {
    app.http.getDictInfo({
      dictType: type
    }).then(res => {
      switch (type) {
        case 20: // 药品单位
          this.setData({
            consumptionlist: res.data
          })
          break;
        case 40: // 包装单位

          break;
        case 51: // 西药用法
          this.setData({
            list: res.data
          })
          break;
        case 52: // 中药服用方法，要求

          break;
        case 60: // 频率
          this.setData({
            list2: res.data
          })
          break;
        case 70: // 中药特殊煎法
          this.setData({
            list: res.data
          })
          break;
        case 103: // 中药服用方法
          res.data.forEach(item => {
            item.usageName = item.dictName
          })
          this.setData({
            list2: res.data
          })
          break;    
        default:
          break;
      }
    }).catch(err => {
      $service.showToast(err.msg)
    })
  },
})